package com.ruoyi.gateway.handler;

import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import com.ruoyi.common.core.exception.CaptchaException;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.gateway.service.ValidateCodeService;
import reactor.core.publisher.Mono;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 * 手机验证码获取
 * @author xysl
 */
@Component
public class XyslCodeHandler implements HandlerFunction<ServerResponse>
{
    @Autowired
    private ValidateCodeService validateCodeService;


    // 中国手机号码正则表达式
    private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";

    @Override
    public Mono<ServerResponse> handle(ServerRequest serverRequest)
    {
        AjaxResult ajax;
        try
        {
            String phone = serverRequest.queryParam("phone").orElse(null);
            // 使用正则表达式进行匹配
            Pattern pattern = Pattern.compile(PHONE_REGEX);
            Matcher matcher = pattern.matcher(phone);
            if (null == phone){
                return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(AjaxResult.error("手机号不能为空!")));
            }else if(phone.length() != 11 || !matcher.matches()){
                return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(AjaxResult.error("手机号格式不正确!")));
            }
            ajax = validateCodeService.generateSmsCode(phone);
        }
        catch (CaptchaException | IOException e)
        {
            return Mono.error(e);
        }
        return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(ajax));
    }
}
